package org.fessingapore.library.services;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import org.fessingapore.library.constants.Constant;
import org.fessingapore.library.constants.LoanStatus;
import org.fessingapore.library.daos.ItemDao;
import org.fessingapore.library.daos.LoanDao;
import org.fessingapore.library.daos.impl.ItemDaoImpl;
import org.fessingapore.library.daos.impl.LoanDaoImpl;
import org.fessingapore.library.models.Item;
import org.fessingapore.library.models.Loan;
import org.springframework.stereotype.Service;

@Service
public class LoanService extends GenericService<Loan>{

	private LoanDao loanDao;
	private ItemDao itemDao;
	
	public LoanService(){
		loanDao = new LoanDaoImpl();
		itemDao = new ItemDaoImpl();
	}

	public Loan borrowItem (Loan loan){

		Item item = loan.getItem();
		try {
			int stock = item.getStock();
			if (stock > 0){
				item.setStock(stock-1);
				itemDao.update(item);			
				loan.setDateBorrowed(Calendar.getInstance().getTime());
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DAY_OF_MONTH, Constant.LOAN_DURATION);
				loan.setDateToReturn(cal.getTime());
				loan.setStatus(LoanStatus.ON_LOAN);
				loan = loanDao.create(loan);
				return loan;
			} else{
				return null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}

	public Loan returnItem (Loan loan){

		Item item = loan.getItem();
		try {
			int stock = item.getStock();
			item.setStock(stock+1);
			itemDao.update(item);
			loan.setDateReturned(Calendar.getInstance().getTime());
			loan.setStatus(LoanStatus.RETURNED);
			loan = loanDao.create(loan);
			return loan;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}
	
	// called by daily scheduler
	public void updateToOverdueLoan() {
		
		List<Loan> overdueLoans = loanDao.findAllNewOverdue();
		for(Loan loan: overdueLoans){
			loan.setStatus(LoanStatus.OVERDUE);
			try {
				loanDao.update(loan);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
